use strict;

use Getopt::Long;

# defaults
my $proc_num  = 16;
my $mess_num  = 1000;
my $retry_num = 3;

&main();

sub main()
{
    &init_vars();

    my @results;
    for ( my $proc_i = 1; $proc_i < $proc_num; $proc_i++ )
    {
        push @results, &iter( $proc_i);
    }

    open( my $fh, ">", "stats/1b") or die "cannot open: $!";
    print $fh "proc_num time\n";
    foreach my $res ( @results)
    {
        $| = 1;
        print $fh ( $res->{proc_num} . " " .  $res->{time}  . "\n"); 
    }
    close $fh;
    return 0; 
}

sub init_vars
{
    my $result = &GetOptions (
        "mess_num=i"   => \$mess_num,
        "proc_num=i"   => \$proc_num,
    );
}

sub cpu_wait
{
    my $time = 3;
    while (1)
    {
        my $cpu = `cat /proc/loadavg`;
        if ( $cpu =~ /^(\d*\.\d*)/)
        {
            if ( $1 < 3.0)
            {
                return;
            } 
        }
        print "Waiting $time. Cpu load $1\n";
        sleep $time;
    }
}

sub iter()
{
    my $proc_num = shift;
    my %res;
   
    $res{proc_num} = $proc_num; 
    $res{time} = 0;

    for ( my $i = 0; $i < $retry_num; $i++)
    {
        &cpu_wait();
        my $res = `mpiexec -n $proc_num ./bin/1b $mess_num 2>err`;
        print "\n!!!" . $proc_num . "\t" . $res . "\n";
        if ( $res =~ /Result\s(\d*)/)
        {
            $res{time}  = ( $res{time}  * $i + $1) / ( $i + 1);
        }
        else
        {
            print "WHAasdasD";
        }
        print $1;
    }
    $res{time}  /= $proc_num / $mess_num;

    return \%res;
}


